package net.huazai.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import net.huazai.config.OSSConfig;
import net.huazai.enums.BizCodes;
import net.huazai.service.FileService;
import net.huazai.utils.ApiResult;
import net.huazai.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 11987
 */
@Service
@Slf4j
public class FileServiceImpl implements FileService{
    /**
     * 注入 OSS 配置文件
     */
    @Autowired
    private OSSConfig ossConfig;

    /**
     * 上传用户头像
     * @param file
     * @return
     */
    @Override
    public String uploadUserAvatar(MultipartFile file) {
        /*
          1、获取 OSS 相关配置
         */
        String endPoint = ossConfig.getEndPoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketName = ossConfig.getBucketName();

        /*
          创建 OSS 对象
         */
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        /*
          获取原始文件名
         */
        String originalFilename = file.getOriginalFilename();

        /*
          获取日期格式，上传时目录名使用
         */
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        /*
          OSS 上传存储路径：user/2024/08/17/xxxxxxx.jpg/png
         */
        String folder = dateTimeFormatter.format(localDateTime);
        // 获取扩展名
        String extension = null;
        if (originalFilename != null){
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        // 新文件名，通过 uuid 生成文件名，
        String fileName = "user/" + folder + "/" + CommonUtil.generateUuid()
                + extension;

        try {
            // 写入 OSS
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, fileName, file.getInputStream());
            // 返回图片路径
            if(putObjectResult != null){
                return "https://" + bucketName + "." + endPoint + "/" + fileName;
            }
        } catch (IOException e) {
            log.error("用户微服务-上传模块-文件上传失败：{}", e.getMessage());
            throw new RuntimeException(e);
        } finally {
            // oss 关闭客户端服务，不然会造成 OOM
            ossClient.shutdown();
        }
        return null;
    }
}